<template>
  <el-select-v2
    v-model="value"
    :options="countryOptions"
    v-bind="$attrs"
    clearable
    filterable
    @change="change"
    :placeholder="props.placeholder"
    multiple
    collapse-tags
  >
  </el-select-v2>
</template>

<script setup>
import useCommonStore from "@/store/modules/common";
import { computed } from "vue";

const commonStore = useCommonStore();
const countryOptions = computed(() => {
  if (!commonStore.countryOptions?.length) {
    commonStore.getCountryList();
  }
  return (
    commonStore.countryOptions.map((i) => {
      return {
        label: i.country_name,
        value: i.country_id, // 使用 country_id 作为 value
      };
    }) || []
  );
});

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
});

const value = computed({
  get: () => {
    return props.modelValue.map((item) => item.country_id); // 返回 country_id 数组
  },
  set: (val) => {
    const selectedCountries = val
      .map((id) => commonStore.countryOptions.find((option) => option.country_id === id))
      .filter((option) => option); // 确保过滤掉未找到的选项
    emit("update:modelValue", selectedCountries);
  },
});

const emit = defineEmits(["update:modelValue", "change"]);
const change = (val) => {
  const selectedCountries = val
    .map((id) => commonStore.countryOptions.find((option) => option.country_id === id))
    .filter((option) => option); // 确保过滤掉未找到的选项
  emit("change", selectedCountries);
};
</script>
